<?php

namespace app\common\service;

use app\common\model\banxi\organization\Organization as OrganizationModel;
use ba\Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\db\exception\PDOException;
use think\exception\ValidateException;

class ExportService extends ApiService
{

    /**
     * header头样式
     * @var array
     */
    protected $styleArray = [
        'font' => ['bold' => true, 'color' => ['rgb' => '000000'], 'size' => '14'],
        'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],
        'borders' => ['outline' => ['borderStyle' => 'thin']],
        'fill' => ['fillType' => 'solid', 'color' => ['rgb' => 'C7C7C7']],
    ];

    /**
     * 上课记录导出
     * @param $list
     * @return array|false
     */
    public function LearnSkRecordExport($list)
    {
        try {
            $organizationModel = new OrganizationModel();
            $organizationBaseInfo = $organizationModel->getOrganizationInfo();
            $exportDate = [];
            foreach ($list as $item) {
                if ($item->studentOrgId == 0) {
                    $organizationName = $organizationBaseInfo['name'];
                } else {
                    $organizationName = $item['organizationBaseInfo']['name'] ?? '';
                }
                $exportDate[] = [
                    'organizationName' => $organizationName,
                    'studentName' => $item->studentInfo->name,
                    'trainerName' => $item->trainerInfo->name,
                    'courseName' => $item->courseName,
                    'courseType' => $item->courseFullTypeCn,
                    'deliveryType' => $item->courseDeliveryTypeCn,
                    'learnTotalNum' => $item->learnTotalNum,
                    'learnCorrectNum' => $item->learnCorrectNum,
                    'learnErrorNum' => $item->learnErrorNum,
                    'actualStartTime' => $item->actualStartTime,
                    'actualEndTime' => $item->actualEndTime,
                    'learnValidStatus' => $item->learnValidStatusCn,
                ];
            }
            $headers = [
                'organizationName' => '机构',
                'studentName' => '学员',
                'trainerName' => '教练',
                'courseName' => '课程',
                'courseType' => '课程类型',
                'deliveryType' => '交付方式',
                'learnTotalNum' => '学习总数',
                'learnCorrectNum' => '正确数',
                'learnErrorNum' => '错误数',
                'actualStartTime' => '上课开始时间',
                'actualEndTime' => '上课结束时间',
                'learnValidStatus' => '是否有效'
            ];
            $res = $this->exportToExcel($exportDate, $headers, '上课记录');
            if (!$res) {
                throw new ValidateException($this->getError());
            }
        } catch (Exception|ValidateException|PDOException $e) {
            $this->setError($e->getMessage());
            return false;
        }
        return $exportDate;
    }

    /**
     * 阅读理解导出
     * @param $list
     * @return array|false
     */
    public function LearnRecordExport($list)
    {
        try {
            $organizationModel = new OrganizationModel();
            $organizationBaseInfo = $organizationModel->getOrganizationInfo();
            $exportDate = [];
            foreach ($list as $item) {
                if ($item->studentOrgId == 0) {
                    $organizationName = $organizationBaseInfo['name'];
                } else {
                    $organizationName = $item['organizationBaseInfo']['name'] ?? '';
                }
                $exportDate[] = [
                    'organizationName' => $organizationName,
                    'studentName' => $item->studentInfo->name,
                    'trainerName' => $item->trainerInfo->name,
                    'courseName' => $item->courseName,
                    'courseType' => $item->courseFullTypeCn,
                    'deliveryType' => $item->courseDeliveryTypeCn,
                    'actualStartTime' => $item->actualStartTime,
                    'actualEndTime' => $item->actualEndTime,
                ];
            }
            $headers = [
                'organizationName' => '机构',
                'studentName' => '学员',
                'trainerName' => '教练',
                'courseName' => '课程',
                'courseType' => '课程类型',
                'deliveryType' => '交付方式',
                'actualStartTime' => '上课开始时间',
                'actualEndTime' => '上课结束时间',
            ];
            $res = $this->exportToExcel($exportDate, $headers, '阅读记录');
            if (!$res) {
                throw new ValidateException($this->getError());
            }
        } catch (Exception|ValidateException|PDOException $e) {
            $this->setError($e->getMessage());
            return false;
        }
        return $exportDate;
    }

    /**
     * 课时记录
     * @param $list
     * @return array|false
     */
    public function coreClassHourDetailExport($list)
    {
        try {
            $exportDate = [];
            foreach ($list as $item) {
                $exportDate[] = [
                    'id' => $item->id,
                    'payerAccountName' => $item->payerAccountName,
                    'receiverAccountName' => $item->receiverAccountName,
                    'businessType' => $item->businessTypeCn,
                    'payAmount' => $item->payAmount,
                    'payType' => $item->payTypeCn,
                    'classHourType' => $item->classHourTypeCn,
                    'classHourNum' => $item->classHourNum,
                    'describe' => $item->describe,
                    'status' => $item->statusCn,
                    'createTime' => $item->createTime,
                ];
            }
            $headers = [
                'id' => '编号',
                'payerAccountName' => '付款方',
                'receiverAccountName' => '收款方',
                'businessType' => '业务类型',
                'payAmount' => '支付金额',
                'payType' => '支付方式',
                'classHourType' => '课时类型',
                'classHourNum' => '课时',
                'describe' => '描述',
                'status' => '状态',
                'createTime' => '交易时间',
            ];
            $res = $this->exportToExcel($exportDate, $headers, '课时记录');
            if (!$res) {
                throw new ValidateException($this->getError());
            }
        } catch (Exception|ValidateException|PDOException $e) {
            $this->setError($e->getMessage());
            return false;
        }
        return $exportDate;
    }


    /**
     * 合伙人名额明细
     * @param $list
     * @return array|false
     */
    public function organizationQuotaRwExport($list)
    {
        try {
            $organizationModel = new OrganizationModel();
            $organizationBaseInfo = $organizationModel->getOrganizationInfo();
            $exportDate = [];
            foreach ($list as $item) {
                if ($item->organizationId == 0) {
                    $organizationName = $organizationBaseInfo['name'];
                } else {
                    $organizationName = $item['organizationBaseInfo']['name'] ?? '';
                }
                $exportDate[] = [
                    'organizationName' => $organizationName,
                    'tradeType' => $item->tradeType ? '增加' : '减少',
                    'value' => $item->value,
                    'beforeValue' => $item->beforeValue,
                    'afterValue' => $item->afterValue,
                    'describe' => $item->describe,
                    'businessType' => $item->businessTypeCn,
                    'createTime' => $item->createTime
                ];
            }
            $headers = [
                'organizationName' => '机构',
                'tradeType' => '交易类型',
                'value' => '数量',
                'beforeValue' => '变更前',
                'afterValue' => '变更后',
                'describe' => '描述',
                'businessType' => '业务类型',
                'createTime' => '交易时间'
            ];
            $res = $this->exportToExcel($exportDate, $headers, '合伙人名额明细');
            if (!$res) {
                throw new ValidateException($this->getError());
            }
        } catch (Exception|ValidateException|PDOException $e) {
            $this->setError($e->getMessage());
            return false;
        }
        return $exportDate;
    }


    public function coreTrainerMonthSalaryExport($list)
    {
        try {
            $exportDate = [];
            foreach ($list as $item) {
                $exportDate[] = [
                    'trainerName' => $item->trainer?->name ?? '',
                    'month' => $item->month,
                    'totalAmount' => $item->totalAmount,
                    'class30Num' => $item->class30Num,
                    'class60Num' => $item->class60Num,
                    'classTrialNum' => $item->classTrialNum,
                    'antiNum' => $item->antiNum,
                    'teachingOnlineNum' => $item->teachingOnlineNum,
                    'teachingOrganizationNum' => $item->teachingOrganizationNum,
                    'teachingVisitNum' => $item->teachingVisitNum,
                ];
            }
            $headers = [
                'trainerName' => '教练',
                'month' => '月份',
                'totalAmount' => '合计',
                'class30Num' => '30分钟课次',
                'class60Num' => '60分钟课次',
                'classTrialNum' => '体验课次',
                'antiNum' => '抗遗忘',
                'teachingOnlineNum' => '线上次数',
                'teachingOrganizationNum' => '机构次数',
                'teachingVisitNum' => '上门'
            ];
            $res = $this->exportToExcel($exportDate, $headers, '薪资计算');
            if (!$res) {
                throw new ValidateException($this->getError());
            }
        } catch (Exception|ValidateException|PDOException $e) {
            $this->setError($e->getMessage());
            return false;
        }
        return $exportDate;
    }

    public function exportToExcel($data, array $headers, string $filename)
    {
        if (!$data) {
            $this->setError('导出数据为空');
            return false;
        }
        if (!$headers) {
            $this->setError('请设置导出的表头');
            return false;
        }
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        // 设置表头

        $sheet->getRowDimension(1)->setRowHeight(40);

        // 填充表头
        $column = 1;
        foreach ($headers as $key => $value) {
            $columnLetter = Coordinate::stringFromColumnIndex($column); // 结果为 'A'
            $sheet->getColumnDimension($columnLetter)->setWidth(20);
            $sheet->getStyle([$column, 1])->applyFromArray($this->styleArray);
            $sheet->setcellvalue([$column, 1], $value);
            $column++;
        }
        // 填充数据
        $row = 2;
        foreach ($data as $item) {
            $column = 1;
            foreach ($headers as $key => $value) {
                $sheet->setcellvalue([$column, $row], $item[$key] ?? '');
                $column++;
            }
            $row++;
        }

        $fileName = urlencode($filename);
        $fileName = str_replace('+', '%20', $fileName);
        $fileName .= ".xlsx";
        // 设置响应头信息
        header("Access-Control-Allow-Origin: *"); // 允许所有域访问
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Encoding: UTF-8');
        header('Access-Control-Expose-Headers: Content-Disposition');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        // header('Cache-Control: max-age=0');

        // 输出Excel文件
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }


}